<template>
  <div class="mobile-detail-container">
    <!-- 顶部导航 -->
    <van-nav-bar title="古建筑彩绘文物调查管理系统" left-arrow @click-left="goBack" @click-right="goToUser" fixed>

      <!-- 右侧用户图标 -->
      <template #right>
        <van-icon name="user" size="18" />
      </template>
    </van-nav-bar>
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <span class="breadcrumb-item" @click="goHome">首页</span>
      <span class="breadcrumb-separator">></span>
      <span class="breadcrumb-item" @click="goToCategory">文物主体管理</span>
      <span class="breadcrumb-separator">></span>
      <span class="breadcrumb-item" @click="gomainpage">{{ categaryname }}</span>
      <span class="breadcrumb-separator">></span>
      <span class="breadcrumb-item">{{ currentRelicname }}</span>
      <span class="breadcrumb-separator">></span>
      <span class="breadcrumb-item">详情</span>
    </div>

    <!-- 加载状态 -->
    <van-loading v-if="loading" class="state-container">加载中...</van-loading>

    <!-- 错误状态 -->
    <van-empty v-else-if="error" description="加载失败，请重试" icon="warning-o">
      <template #bottom>
        <van-button type="primary" size="small" @click="fetchRelicData">重试</van-button>
      </template>
    </van-empty>

    <!-- 无数据 -->
    <van-empty v-else-if="!currentRelic" description="暂无文物数据" />

    <!-- 详情内容 -->
    <div v-else class="detail-content">
      <!-- 文物主图 -->
      <van-cell-group title="文物主图" class="section-card">
        <div class="main-image-wrapper">
          <van-image :src="currentRelic.image_base64 || currentRelic.image" fit="contain" class="main-image"
            @click="previewImage(currentRelic.image_base64 || currentRelic.image)" @error="handleImageError('主图')">
            <template #error>
              <div class="image-error">
                <van-icon name="photo" />
                <p>主图加载失败</p>
              </div>
            </template>
          </van-image>
          <van-button type="success" size="small" block
            @click="handleDownloadImage('image', currentRelic.id, currentRelic.image, '0')" style="margin-top: 10px">
            下载原图
          </van-button>
        </div>
      </van-cell-group>

      <!-- 名称与描述 -->
      <div class="section-card">
        <div class="section-title">名称与描述</div>
        <div class="custom-cell">
          <div class="cell-label" style="flex: 0 0 20%;">名称：</div>
          <div class="cell-value" style="flex: 1;">{{ currentRelic.name || '未知' }}</div>
        </div>
        <div class="custom-cell">
          <div class="cell-label" style="flex: 0 0 20%;">彩画做法：</div>
          <div class="cell-value" style="flex: 1;">
            <van-text-ellipsis rows="2" :content="currentRelic.current_damage_status" expand-text="展开"
              collapse-text="收起" />
          </div>
        </div>
      </div>

      <!-- 基本信息 -->
      <div class="section-card">
        <div class="section-title">基本信息</div>
        <div class="custom-cell">
          <div class="cell-label" style="flex: 0 0 20%;">彩画主题：</div>
          <van-text-ellipsis rows="2" :content="currentRelic.painting_theme" expand-text="展开" collapse-text="收起" />
          <!-- <div class="cell-value" style="flex: 1;">{{ currentRelic.painting_theme || '未知' }}</div> -->
        </div>
        <div class="custom-cell">
          <div class="cell-label" style="flex: 0 0 20%;">纹样类型：</div>
          <div class="cell-value" style="flex: 1;">{{ currentRelic.pattern_types || '未知' }}</div>
        </div>
        <div class="custom-cell">
          <div class="cell-label" style="flex: 0 0 20%;">构图形式：</div>
          <div class="cell-value" style="flex: 1;">{{ currentRelic.composition_style || '未知' }}</div>
        </div>
        <div class="custom-cell">
          <div class="cell-label" style="flex: 0 0 20%;">主色调：</div>
          <div class="cell-value" style="flex: 1;">{{ currentRelic.dominant_colors || '未知' }}</div>
        </div>
      </div>

      <!-- 病害情况 -->
      <div class="section-card">
        <div class="section-title">病害情况</div>
        <div class="custom-cell">
          <div class="cell-label" style="flex: 0 0 20%;">病害类型：</div>
          <div class="cell-value" style="flex: 1;">{{ currentRelic.disease_types || '未知' }}</div>
        </div>
        <div class="custom-cell">
          <div class="cell-label" style="flex: 0 0 20%;">病害程度：</div>
          <div class="cell-value" style="flex: 1;">{{ diseaseSeverityText }}</div>
        </div>
      </div>

      <!-- 现状与残损 -->
      <div class="section-card">
        <div class="section-title">现状与残损情况</div>
        <div class="custom-cell full-ellipsis">
          <van-text-ellipsis rows="3" :content="currentRelic.current_damage_status" expand-text="展开"
            collapse-text="收起" />
        </div>
      </div>

      <!-- 病害图片列表 -->
      <div class="section-card">
        <div class="section-title">状态图像 ({{ currentRelic.disease_images?.length || 0 }}张)</div>
        <div v-if="currentRelic.disease_images?.length === 0" class="empty-images">
          <van-empty description="暂无病害图片" />
        </div>
        <div v-else>
          <div class="image-list">
            <div v-for="img in currentRelic.disease_images" :key="img.id" class="image-item"
              @click="toggleImageSelection(img.id)">
              <van-image :src="img.image_base64 || img.image_url" fit="contain" class="thumb-image"
                @click.stop="previewImage(img.image_base64 || img.image_url)"
                @error="handleImageError(`病害图-${img.id}`)">
                <template #error>
                  <van-icon name="photo" />
                </template>
              </van-image>
              <div class="image-info">
                <div class="image-name">图像名称：{{ img.image_name || '未命名' }}</div>
                <div class="image-desc">图像描述：{{ img.image_description || '暂无描述' }}</div>
                <div class="image-time">上传时间：{{ formatDate(img.created_at) }}</div>
              </div>
              <van-checkbox v-model="selectedImageIdsSet[img.id]" shape="square"
                @click="toggleImageSelection(img.id)" />
            </div>
          </div>
          <div style="padding: 10px">
            <van-button type="primary" block @click="submitComparison"
              :disabled="Object.keys(selectedImageIdsSet).filter(k => selectedImageIdsSet[k]).length !== 2">
              比对选中图片
            </van-button>
          </div>
        </div>
      </div>

      <!-- 比对结果展示 -->
      <div v-if="showComparisonResult" class="comparison-result">
        <van-cell-group title="比对结果">
          <div class="similarity-info">
            <span>相似度：</span>
            <strong class="similarity-value">{{ comparisonResult.similarity }}%</strong>
            <van-progress :percentage="comparisonResult.similarity" color="#07c160" />
          </div>
          <div class="comparison-images">
            <div class="comp-item">
              <p>图片1</p>
              <van-image :src="getImageUrlById(selectedImageIds[0])" fit="contain" class="comp-image"
                @click="previewImage(getImageUrlById(selectedImageIds[0]))" />
            </div>
            <div class="comp-item">
              <p>图片2</p>
              <van-image :src="getImageUrlById(selectedImageIds[1])" fit="contain" class="comp-image"
                @click="previewImage(getImageUrlById(selectedImageIds[1]))" />
            </div>
            <div class="comp-item">
              <p>差异图</p>
              <van-image :src="comparisonResult.diffImageUrl" fit="contain" class="comp-image diff"
                @click="previewImage(comparisonResult.diffImageUrl)" @error="showFailToast('差异图加载失败')" />
            </div>
          </div>
          <van-button type="default" size="small" block @click="resetComparison">重新选择</van-button>
        </van-cell-group>
      </div>

      <!-- 数据文件 -->
      <div class="section-card">
        <div class="section-title">数据文件</div>
        <template v-if="currentRelic.hasSpectrum && currentRelic.spectrum_file_url">
          <div class="custom-cell file-cell">
            <div class="cell-label" style="flex: 0 0 30%;">光谱数据文件</div>
            <div class="cell-value" style="flex: 1;">
              <div class="file-info">
                大小：{{ formatFileSize(currentRelic.spectrum_file_size) }} |
                {{ formatDate(currentRelic.spectrum_uploaded_at) }}
              </div>
              <van-button size="small" type="primary"
                @click="handleDownload('spectrum', currentRelic.id, currentRelic.spectrum_file_name)">
                下载
              </van-button>
            </div>
          </div>
        </template>

        <template v-if="currentRelic.hasThreeD && currentRelic.threeD_file_url">
          <div class="custom-cell file-cell">
            <div class="cell-label" style="flex: 0 0 30%;">三维数据文件</div>
            <div class="cell-value" style="flex: 1;">
              <div class="file-info">
                大小：{{ formatFileSize(currentRelic.threeD_file_size) }} |
                {{ formatDate(currentRelic.threeD_uploaded_at) }}
              </div>
              <div>
                <van-button size="small" type="primary"
                  @click="handleDownload('3d', currentRelic.id, currentRelic.threeD_file_name)"
                  style="margin-right: 5px">
                  下载
                </van-button>
                <van-button size="small" type="success" @click="showPointCloud = true">
                  查看
                </van-button>
              </div>
            </div>
          </div>
        </template>

        <div v-if="!currentRelic.hasSpectrum && !currentRelic.hasThreeD" class="empty-data">
          暂无数据文件
        </div>
      </div>

      <!-- 时间信息 -->
      <div class="section-card">
        <div class="section-title">时间信息</div>
        <div class="custom-cell">
          <div class="cell-label" style="flex: 0 0 30%;">创建时间</div>
          <div class="cell-value" style="flex: 1;">{{ formatDate(currentRelic.created_at) || '未知' }}</div>
        </div>
        <div v-if="currentRelic.last_modified_at" class="custom-cell">
          <div class="cell-label" style="flex: 0 0 30%;">最后修改</div>
          <div class="cell-value" style="flex: 1;">{{ formatDate(currentRelic.last_modified_at) }}</div>
        </div>
      </div>
    </div>
    <!-- 编辑按钮 -->
    <div class="center-button">
      <van-button type="primary" size="normal" round @click="goToEdit">
        编辑文物信息
      </van-button>
    </div>
        <!-- 点云弹窗 -->
    <van-popup
      v-model:show="showPointCloud"
      round
      closeable
      width="90%"
      :style="{ height: '60vh' }"
      close-icon="cross"
      title="三维点云预览"
    >
    <mobilePointCloudViewer :relic-id="currentRelic.id" />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { useRelicDetail } from '@/components/composables/useRelicDetail'
import { onMounted, ref} from 'vue'
import myaxios from '@/auth/auth.service.js'
import mobilePointCloudViewer from './mobilePointCloudViewer.vue'
import { showFailToast, showToast, showImagePreview } from 'vant'
import { ElLoading } from 'element-plus'

// 使用数据逻辑
const {
  loading,
  error,
  currentRelic,
  currentRelicname,
  categaryid,
  categaryname,
  diseaseSeverityText,
  goHome,
  goToUser,
  goToCategory,
  gomainpage,
  fetchRelicData,
  getBuildingTypeText,
  formatDate,
  goBack,
  goToEdit,
  handleDeleteImage,
} = useRelicDetail()

// 点云弹窗
const showPointCloud = ref(false)

// 页面加载
onMounted(() => {
  if (!currentRelic.value && !loading.value && !error.value) {
    fetchRelicData()
  }
})

// 图片错误处理
const handleImageError = (type: string) => {
  showFailToast(`${type}加载失败`)
}

// 文件下载
const handleDownload = async (fileType: string, relicId: number, filename: string) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '准备下载...',
    background: 'rgba(0, 0, 0, 0.1)',
  })
  filename = filename.split('.')[0]
  try {
    await myaxios.downloadFile(fileType, relicId, filename)
  } catch (error) {
    // 错误已在API中处理，这里可以添加额外逻辑
  } finally {
    loadingInstance.close()
  }
}


const handleDownloadImage = async (
  fileType: string,
  relicId: number,
  fileurl: string,
  imageId: string,
) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '准备下载...',
    background: 'rgba(0, 0, 0, 0.1)',
  })
  const filename = fileurl.split('/').pop()
  const decodedFilename = decodeURIComponent(filename)

  try {
    await myaxios.downloadFile(fileType, relicId, decodedFilename, imageId)
  } catch (error) {
    // 错误已在API中处理，这里可以添加额外逻辑
  } finally {
    loadingInstance.close()
  }
}

// 格式化文件大小
const formatFileSize = (size?: number) => {
  if (!size) return '未知大小'
  const units = ['B', 'KB', 'MB', 'GB']
  let i = 0
  let s = size
  while (s >= 1024 && i < units.length - 1) {
    s /= 1024
    i++
  }
  return `${s.toFixed(2)} ${units[i]}`
}

const previewImage = (src: string) => {
  if (src) {
    showImagePreview([src])
  }
}
// 选中图片（使用对象映射）
const selectedImageIdsSet = ref<Record<number, boolean>>({})

// 提交比对
const submitComparison = async () => {
  const selectedIds = Object.keys(selectedImageIdsSet.value)
    .filter(k => selectedImageIdsSet.value[Number(k)])
    .map(Number)

  if (selectedIds.length !== 2) {
    showToast('请选择2张图片进行比对')
    return
  }

  comparing.value = true
  try {
    const response = await myaxios.compareDiseaseImages({
      relic_id: currentRelic.value.id,
      image_ids: selectedIds,
    })

    comparisonResult.value = {
      similarity: response.data.similarity,
      diffImageUrl: response.data.diff_image_base64,
    }
    selectedImageIds.value = selectedIds
    showComparisonResult.value = true
  } catch (error) {
    console.error('比对失败', error)
    showFailToast('比对失败，请重试')
  } finally {
    comparing.value = false
  }
}

// 状态
const comparing = ref(false)
const showComparisonResult = ref(false)
const comparisonResult = ref<{
  similarity: number
  diffImageUrl: string
} | null>(null)
const selectedImageIds = ref<number[]>([])

// 重置比对
const resetComparison = () => {
  selectedImageIdsSet.value = {}
  showComparisonResult.value = false
  comparisonResult.value = null
  selectedImageIds.value = []
}

// 获取图片URL
const getImageUrlById = (imageId: number) => {
  const image = currentRelic.value.disease_images.find((img: any) => img.id === imageId)
  return image ? image.image_base64 || image.image_url : ''
}

// 切换选中状态（最多2张）
const toggleImageSelection = (id: number, event?: MouseEvent) => {
  if (event && (event.target as HTMLElement).classList.contains('van-image')) return; // 如果点击的是图片，则不执行选择操作

  const selected = Object.keys(selectedImageIdsSet.value).filter(k => selectedImageIdsSet.value[Number(k)]).map(Number);
  if (selected.includes(id)) {
    selectedImageIdsSet.value[id] = false;
  } else {
    if (selected.length >= 2) {
      showToast('最多选择2张');
      return;
    }
    selectedImageIdsSet.value[id] = true;
  }
};
</script>

<style scoped>
.mobile-detail-container {
  padding-top: 46px;
  font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.mobile-detail-container {
  font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.mobile-upload-container {
  padding-top: 46px;
  min-height: 100vh;
  background-color: #f7f8fa;
}


/* 通用卡片 */
.section-card {
  margin: 10px;
  padding: 0;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}

/* 自定义标题 */
.section-title {
  padding: 12px 1px;
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  background-color: #f8f8f8;
  border-bottom: 1px solid #e8e8e8;
}

/* 自定义信息项 */
.custom-cell {
  display: flex;
  padding: 12px 0px;
  border-bottom: 1px solid #f2f2f2;
  font-size: 14px;
  color: #333;
}

.custom-cell:last-child {
  border-bottom: none;
}

.cell-label {
  font-weight: 500;
  color: #333;
  text-align: right;
  padding-right: 12px;
}

.cell-value {
  color: #555;
  line-height: 1.5;
}

/* 多行文本居中 */
.full-ellipsis {
  padding: 12px 16px;
  border-bottom: 1px solid #f2f2f2;
}

/* 文件项特殊样式 */
.file-cell .cell-value {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.file-info {
  color: #888;
  font-size: 13px;
}

/* 图片列表 */
.image-list {
  padding: 0 16px;
}

.image-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f2f2f2;
}

.thumb-image {
  width: 80px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
  margin-right: 12px;
}

.image-info {
  flex: 1;
}

.image-name {
  font-size: 15px;
  font-weight: 500;
  color: #333;
}

.image-desc,
.image-time {
  font-size: 12px;
  color: #888;
  margin: 4px 0;
}

/* 比对结果 */
.comparison-result {
  margin: 10px;
}

.similarity-info {
  padding: 12px 16px;
  background-color: #f0f8f0;
  border-radius: 8px;
  margin-bottom: 15px;
  font-size: 14px;
  color: #333;
}

.similarity-value {
  color: #07c160;
  font-size: 18px;
  margin: 0 10px;
}

.comparison-images {
  display: flex;
  gap: 10px;
  overflow-x: auto;
  padding: 10px 0;
}

.comp-item {
  min-width: 150px;
  text-align: center;
}

.comp-image {
  width: 100%;
  height: 120px;
  object-fit: contain;
  background-color: #f5f5f5;
  border-radius: 6px;
}

.diff {
  border: 2px solid #fa541c;
}

/* 空状态 */
.empty-images,
.empty-data {
  padding: 20px 0;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* 主图区域 */
.main-image-wrapper {
  padding: 16px;
}

.main-image {
  width: 100%;
  height: 200px;
  object-fit: contain;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.center-button {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中（如果需要的话）*/
  padding-top: 1%;
  /* 可选，根据需要调整顶部间距 */
  margin-bottom: 1%;
}

/* 面包屑样式 */
.breadcrumb {
  padding: 8px 16px;
  background-color: #f7f8fa;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  /* 确保不被 fixed 的 nav-bar 遮挡 */
  margin-top: 0px;
  /* van-nav-bar 的默认高度 */
}

.breadcrumb-item {
  color: #1989fa;
  /* 可点击项用蓝色 */
}

.breadcrumb-item:last-child {
  color: #333;
  font-weight: 500;
}

.breadcrumb-separator {
  margin: 0 1px;
  color: #999;
}
</style>
